package com.generator.util;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.Map;

public class FreemarkerUtil {



    static Template temp;


    public static String generator(String content, Map<String, Object> map)  {
       return generator("content.ftl",content,map);
    }
    public static String generator(String filename,String content, Map<String, Object> map)  {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        stringTemplateLoader.putTemplate(filename,content);
        cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_29));
        cfg.setTemplateLoader(stringTemplateLoader);
        StringWriter  fw = new StringWriter();
        try {
            temp = cfg.getTemplate(filename);
            temp.process(map, fw);
            return fw.toString();
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fw.flush();
                fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
    public static void initConfig(String ftlPath,String ftlName)  {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
        try {
            cfg.setDirectoryForTemplateLoading(new File(ftlPath));
            cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_29));
            cfg.setSharedVariable(FormatDirective.DIRECTIVE_NAME, new FormatDirective());
            temp = cfg.getTemplate(ftlName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void generatorRule(String fileName, Map<String, Object> map)  {
        FileWriter fw = null;
        try {
            fw = new FileWriter(fileName);
            BufferedWriter bw = new BufferedWriter(fw);
            temp.process(map, bw);
            bw.flush();
            fw.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }

    }
}
